﻿namespace 聚合_分组
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>()
            {
                new Student(){ Id=1, Name="张三", Age=18 ,Salary=3000},
                new Student(){ Id=2, Name="李四", Age=20 ,Salary=6000},
                new Student(){ Id=3, Name="王五", Age=17 ,Salary=9000},
                new Student(){ Id=4, Name="赵六", Age=18 ,Salary=5000},
                new Student(){ Id=5, Name="前七", Age=20 ,Salary=4001},
            };

            //最大年龄
            var maxAge = students.Max(s => s.Age);
            Console.WriteLine($"最大年龄：{maxAge}");

            var maxValue = students.Max(s =>
            {
                if (s.Age < 19)
                    return s.Age * 2;
                else
                    return s.Age + 5;
            });

            Console.WriteLine($"maxValue = {maxValue}");

            //下面预计会报错，因为Student类没有实现IComparable接口
            //Console.WriteLine(students.Max());

            //按年龄分组，计算每组的最大工资、最小工资、平均工资
            //var groupResult = students.GroupBy(s => s.Age)    //这是自动生成的代码
            //    .Select(g => new
            //    {
            //        Age = g.Key,
            //        MaxSalary = g.Max(s => s.Salary),
            //        MinSalary = g.Min(s => s.Salary),
            //        AvgSalary = g.Average(s => s.Salary)
            //    });

            IEnumerable<IGrouping<int, Student>> temp = students.GroupBy(s => s.Age);
            foreach (IGrouping<int, Student> group in temp)
            {
                Console.WriteLine($"分组键值：{group.Key}    该组最大工资：{group.Max(s => s.Salary)}   平均工资：{group.Average(s => s.Salary)}");
                foreach (Student s in group)
                {
                    Console.WriteLine(s);                    
                }
                Console.WriteLine("\n---------------------------------------\n");
            }
        }
    }

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public int Salary { get; set; }

        override public string ToString()
        {
            return $"Id:{Id}, Name:{Name}, Age:{Age}, Salary:{Salary}";
        }
    }
}
